package com.charles.video.common.security.interceptor;

import com.charles.video.api.model.MemberLogin;
import com.charles.video.common.core.constant.SecurityConstants;
import com.charles.video.common.core.context.SecurityContextHolder;
import com.charles.video.common.core.utils.Convert;
import com.charles.video.common.core.utils.ServletUtils;
import com.charles.video.common.core.utils.StringUtils;
import com.charles.video.common.security.auth.AuthUtil;
import com.charles.video.common.security.utils.SecurityUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Charles-H
 * <p>
 * 自定义请求头拦截器
 */
@Component
public class HeaderInterceptor implements AsyncHandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) return true;

        /** 在这里将请求头的信息全部丢入线程 */
        SecurityContextHolder.setMemberKey(ServletUtils.getHeader(request, SecurityConstants.MEMBER_KEY));
        SecurityContextHolder.setMemberId(Convert.toInt(ServletUtils.getHeader(request, SecurityConstants.MEMBER_ID), 0));
        SecurityContextHolder.setMemberNum(ServletUtils.getHeader(request, SecurityConstants.MEMBER_NUM));
        SecurityContextHolder.setMemberRole(ServletUtils.getHeader(request, SecurityConstants.MEMBER_ROLE));

        String token = SecurityUtils.getToken();
        if (StringUtils.isNotEmpty(token)) {
            MemberLogin memberLogin = AuthUtil.getMemberLogin(token);
            if (StringUtils.isNotNull(memberLogin)) {
                AuthUtil.verifyUserLoginExpire(memberLogin);
                SecurityContextHolder.set(SecurityConstants.MEMBER_LOGIN, memberLogin);
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        SecurityContextHolder.remove();
    }
}
